package com.huawei.esdk.oa.device.exchange.convert;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import microsoft.exchange.webservices.data.Appointment;
import microsoft.exchange.webservices.data.Attendee;
import microsoft.exchange.webservices.data.AttendeeCollection;
import microsoft.exchange.webservices.data.ServiceLocalException;

import com.huawei.esdk.tp.domain.model.Conference;
import com.huawei.esdk.tp.domain.model.SiteInConference;

public class ExchangeConfMgrConvert 
{

	public void convertExchangeConfModal2South(Conference conferenceInfo,
			Appointment appointment) throws Exception 
	{

		appointment.setSubject(conferenceInfo.getName());

		appointment.setStart(conferenceInfo.getBeginTime());

		Date endDate = new Date(convertminutesToMilliseconds(conferenceInfo.getLength())
				+ conferenceInfo.getBeginTime().getTime());
		appointment.setEnd(endDate);

		appointment.setLocation(getExchangeMeetingLocation(conferenceInfo.getSites()));

		setExchangeMeetingResources(conferenceInfo.getSites(),
				appointment.getResources());
	}
	
	public Conference getTpConfSouth2Modal(Appointment appointment) throws ServiceLocalException
	{
	    Conference conf = null;
	    if(null != appointment)
	    {
            conf = new Conference(appointment.getId().getUniqueId());
            conf.setName(appointment.getSubject());
            conf.setBeginTime(appointment.getStart());
            conf.setLength((int)appointment.getDuration().getTotalMinutes());
            
            List<SiteInConference> sites = new ArrayList<SiteInConference>();
            setTPConfSites(appointment.getResources(), sites);
            conf.setSites(sites);
	    }
	    return conf;
	}
	
    private String getExchangeMeetingLocation(List<SiteInConference> sites)
    {
        StringBuffer sb = new StringBuffer();
        if(null != sites)
        {
	        for (SiteInConference site : sites)
	        {
		       sb.append(site.getName()).append(";");
	        }
        }
        return sb.toString();
    }
    
    private void setExchangeMeetingResources(List<SiteInConference> sites, AttendeeCollection attendeeCollection)
    {
    	attendeeCollection.clear();
    	
        for (SiteInConference site : sites)
        {
	        Attendee attendee = new Attendee();
	        attendee.setAddress(site.getUri());
	        attendee.setName(site.getName());
	        attendeeCollection.add(attendee);
        }
    }
    
    private void setTPConfSites(AttendeeCollection attendeeCollection, List<SiteInConference> sites)
    { 
        for (Attendee attendee : attendeeCollection)
        {
            SiteInConference tpSite = new SiteInConference();
            tpSite.setUri(attendee.getAddress());
            tpSite.setName(attendee.getName());
            sites.add(tpSite);
        }
    }

    public long convertminutesToMilliseconds(int minutes) 
    { 
    	return 1000L*60*minutes; 
    } 

}
